<?php

namespace App\Listeners;

use App\Events\ConfirmReceiptEvent;
use App\Forms\OrderForms;
use App\Forms\UserForms;
use App\Models\OrderDetail;
use App\Models\UserBalanceLog;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class CommissionListeners
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ConfirmReceiptEvent  $event
     * @return void
     */
    public function handle(ConfirmReceiptEvent $event)
    {
        //
        $order = $event->order;

        if($order->pid && $order->commission_amount > 0){

            /**
             * @var OrderDetail $orderDetail
             */
            $orderDetail = (new OrderForms())->orderDetailList($order->id)[0];

            $userForms = new UserForms();

            $parent = $userForms->getUserDetail($order->pid);

            //生成余额记录
            $userForms->balanceLogCreate([
                'uid'    => $order->pid,
                'amount' => $order->commission_amount,
                'type'   => UserBalanceLog::COMMISSION_IN,
                'msg'    => '下级购买' . ($orderDetail->good_name ?? '商品') . '分销'
            ]);

            //累增父级余额
            $parent->update([
                'balance' => bcadd($parent->balance, $order->commission_amount, 2)
            ]);

        }

    }
}
